package com.yeskery.nut.plugin;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.core.NutException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认绑定上下文
 * @author sprout
 * @version 1.0
 * 2022-05-29 21:57
 */
public class DefaultBindContext implements RemovableBindContext {

    /** 数据map */
    private final Map<Class<?>, Object> objectMap = new ConcurrentHashMap<>();

    /** Nut应用对象 */
    private final NutApplication nutApplication;

    /**
     * 构建默认绑定上下文
     * @param nutApplication Nut应用对象
     */
    public DefaultBindContext(NutApplication nutApplication) {
        this.nutApplication = nutApplication;
    }

    @Override
    public NutApplication getNutApplication() {
        return nutApplication;
    }

    @Override
    public void bindObject(Class<?> clazz, Object object) {
        if (objectMap.containsKey(clazz)) {
            throw new NutException("The Corresponding Key [" + clazz.getName() + "] Already Exists.");
        }
        objectMap.put(clazz, object);
    }

    @Override
    public <T> void removeObject(Class<T> clazz) {
        objectMap.remove(clazz);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getObject(Class<T> clazz) {
        T object = (T) objectMap.get(clazz);
        if (object == null) {
            for (Map.Entry<Class<?>, Object> entry : objectMap.entrySet()) {
                if (entry.getKey().isAssignableFrom(clazz)) {
                    return (T) entry.getValue();
                }
            }
        }
        return object;
    }
}
